package com.jiuyuejiu.func_video.videosync;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.jiuyuejiu.R;
import com.jiuyuejiu.application.ConstValues;
import com.jiuyuejiu.base.BaseActivity;
import com.jiuyuejiu.func_video.VideoService;
import com.jiuyuejiu.func_video.domain.VideoFenleiStc;
import com.jiuyuejiu.utils.ShanHaiUtil;
import com.kylin.core.loader.LatteLoader;
import com.kylin.core.utils.dbtutil.FileUtil;
import com.kylin.core.utils.dbtutil.FunUtil;
import com.kylin.core.utils.dbtutil.PrefUtils;

import java.io.File;
import java.lang.ref.SoftReference;
import java.util.ArrayList;

import me.yokeyword.fragmentation.anim.DefaultHorizontalAnimator;
import me.yokeyword.fragmentation.anim.FragmentAnimator;

/**
 * 每个视频分类列表同步
 */
public class VideoSyncActivity extends BaseActivity implements View.OnClickListener {

    private static final RequestOptions BANNER_OPTIONS = new RequestOptions()
            .diskCacheStrategy(DiskCacheStrategy.ALL)// 缓存SOURC和RESULT
            .dontAnimate()// 移除所有的动画
            // .fitCenter()// 该api可能 铺不满整个ImageView控件
            // .centerCrop()// 按比例放大/缩小,铺满整个ImageView控件
            .placeholder(R.drawable.shape_solid_gray_5)// 占位图
            .transform(new CenterCrop(), new RoundedCorners(14));

    private ImageView img;

    private VideoService service;
    private MyHandler handler;

    private String lastCatName;
    private ArrayList<VideoFenleiStc> videoFenleiStcs;

    // 是否下载所有分类目录文件 默认:true  true:需要下载  false:不需要下载
    private boolean downAllFile;

    /**
     * 接收子线程消息的 Handler
     */
    public static class MyHandler extends Handler {

        // 软引用
        SoftReference<VideoSyncActivity> fragmentRef;

        public MyHandler(VideoSyncActivity fragment) {
            fragmentRef = new SoftReference<VideoSyncActivity>(fragment);
        }

        @Override
        public void handleMessage(Message msg) {
            VideoSyncActivity fragment = fragmentRef.get();
            if (fragment == null) {
                return;
            }
            Bundle bundle = msg.getData();

            // 处理UI 变化
            switch (msg.what) {
                case ConstValues.WAIT1: // 下载文件的回调
                    fragment.downloadFileSuc(bundle);
                    break;
            }
        }
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 全屏
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_video_sync);

        // 初始化视图
        initView();
        // 初始化数据
        initData();
    }

    // 初始化视图
    private void initView() {

        img = (ImageView) findViewById(R.id.video_sync_img);

    }

    // 初始化数据
    private void initData() {

        handler = new MyHandler(VideoSyncActivity.this);
        service = new VideoService(VideoSyncActivity.this, handler);


        Glide.with(VideoSyncActivity.this)
                .load(ConstValues.WANGZHEYINGDI)
                .apply(BANNER_OPTIONS)
                .into(img);

        // 获取上一页传递过来的数据
        Intent i = getIntent();
        lastCatName = (String) i.getSerializableExtra("categoryname");
        videoFenleiStcs = (ArrayList<VideoFenleiStc>) i.getSerializableExtra("videoFenleiStcs");

        // 下载每个分类的视频列表
        if (videoFenleiStcs == null || videoFenleiStcs.size() <= 0) {
            Toast.makeText(VideoSyncActivity.this, "未找到指定分类", Toast.LENGTH_SHORT).show();
            VideoSyncActivity.this.finish();
        } else {

            // 下载每个分类的视频列表
            downloadVideoList();
        }

    }

    // ----↓ 下载每个分类的视频列表 2021/12/17 2:03 下午 ↓------------------------------------------------------------------------------------
    // 下载每个分类的视频列表
    private void downloadVideoList() {
        if (hasPermission(ConstValues.WRITE_READ_EXTERNAL_PERMISSION)) {
            // 拥有了此权限,那么直接执行业务逻辑
            // 先下载所有视频记录
            downVideoUrlAndRead();
        } else {
            // 还没有对一个权限(请求码,权限数组)这两个参数都事先定义好
            requestPermission(ConstValues.WRITE_READ_EXTERNAL_CODE, ConstValues.WRITE_READ_EXTERNAL_PERMISSION);
        }
    }

    // 手动拥有读写权限后 执行下载文件
    @Override
    public void doWriteSDCard() {
        try {
            // 拥有了此权限,那么直接执行业务逻辑
            // 先下载所有视频记录
            downVideoUrlAndRead();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 先下载所有视频记录
    private void downVideoUrlAndRead() {

        LatteLoader.showLoading(VideoSyncActivity.this);

        // 循环下载所有分类记录的视频
        for (VideoFenleiStc videoFenleiStc : videoFenleiStcs) {

            String fileName = FunUtil.StringToMd5(lastCatName + videoFenleiStc.getCategory());
            FileUtil.deleteFile(new File(ShanHaiUtil.parseFilePath(fileName)));// 先删除
            String downurl = ShanHaiUtil.getHttpid() + ConstValues.LANDKING + "/" + lastCatName + "/" + videoFenleiStc.getCategory() + "/" + ConstValues.TXTNAME;

            // 请求
            service.downCatVideoJsonList(downurl,// 请求url
                    fileName, // 本地存储名称
                    false, // 是否显示进度条 false不显示下载进度,true显示下载进度框
                    ConstValues.WAIT1);// 用于当前Activity界面handle的对应回调接收 比如what1,what2

        }
    }

    // 下载文件的回调
    private int fenleicount = 0;

    private void downloadFileSuc(Bundle bundle) {

        String formjson = bundle.getString("formjson");
        String status = bundle.getString("status");

        if (ConstValues.SUCCESS.equals(status)) {
            fenleicount++;
            if (fenleicount >= videoFenleiStcs.size()) {// 下载完成

                // 是否重新下载每个分类的视频列表 默认true true需要重新下载  false不需要重新下载
                PrefUtils.putBoolean(VideoSyncActivity.this, ConstValues.ISGETVIDEOURL, false);


                LatteLoader.stopLoading();

                //数据是使用Intent返回
                Intent intent = new Intent();
                //把返回数据存入Intent
                intent.putExtra("result", "Success");
                //设置返回数据
                VideoSyncActivity.this.setResult(RESULT_OK, intent);
                //关闭Activity
                VideoSyncActivity.this.finish();
            }

        } else {
            Toast.makeText(VideoSyncActivity.this, formjson, Toast.LENGTH_SHORT).show();
        }
    }
    // ----↑ 下载每个分类的视频列表 2021/12/17 2:03 下午 ↑------------------------------------------------------------------------------------


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            /* case R.id.top_navigation_rl_back:
                this.finish();
                break;*/
        }
    }

    @Override
    public FragmentAnimator onCreateFragmentAnimator() {
        // 设置横向(和安卓4.x动画相同)
        return new DefaultHorizontalAnimator();
        // return new DefaultNoAnimator();
    }


    @Override
    protected void onPause() {
        super.onPause();
    }
}
